import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'
import { CommentService } from './services/comment.service'

@Component({
  selector: 'app-comment',
  templateUrl: './comment.component.html',
  styleUrls: ['./comment.component.scss']
})
export class CommentComponent implements OnInit {
  list = []
  nomore = false
  error = false
  loading = false

  constructor(private location: Location, private service: CommentService) {
    // 触底分页
    window.onscroll = e => {
      let clientHeight = document.documentElement.clientHeight
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      let scrollHeight = document.body.scrollHeight
      // 触底了
      if (scrollTop + clientHeight === scrollHeight) {
        setTimeout(() => {
          if (!this.nomore && !this.error) {
            this.getList(this.service.reqdata.pager.Start)
          }
        }, 1000)
      }
    }
  }

  ngOnInit() {
    this.loading = true
    this.getList(0)
  }
  onClickLeft() {
    this.location.back()
  }
  getList(start) {
    this.service.getList(
      start,
      res => {
        setTimeout(() => {
          this.error = false
          this.loading = false
        }, 500)
        if (res.Success && res.Result) {
          // 下一次的起始条目需要加上本次请求到的数据条数
          this.service.reqdata.pager.Start += res.Result.Value.length
          // 如果本次请求到的数据小于每页总数，说明没有下一页了
          if (res.Result.Value.length < this.service.reqdata.pager.Limit) {
            this.nomore = true
          } else {
            this.nomore = false
          }
          // 数据处理
          let data = res.Result.Value.map(item => {
            if (item.LayoutReference) {
              item.LayoutReference.Photo = ''
            }
            let obj = {
              Id: item.Id,
              Content: item.Content,
              DateTime: item.DateTime,
              Praise: item.Praise,
              Photo: item.Photo ? true : false,
              LayoutReference: item.LayoutReference,
              ProjectSearchView: item.ProjectSearchView
            }
            return obj
          })
          // 如果是第一页，那先把数据清空
          if (start === 0) {
            this.list = []
          }
          this.list = this.list.concat(data)
        } else {
          this.nomore = false
        }
      },
      err => {
        setTimeout(() => {
          this.error = true
          this.loading = false
        }, 500)
      }
    )
  }
  trackByFn(index, item) {
    return item.Id
  }
  handleReload() {
    this.error = false
    this.loading = true
    this.getList(this.service.reqdata.pager.Start)
  }
}
